package com.shj.em.biz.sys.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.shj.em.aa.entity.User;
import com.shj.em.aa.service.UserService;
import com.shj.em.base.support.ResCode;
import com.shj.em.common.to.Tree;
import com.shj.em.aa.entity.Resource;
import com.shj.em.aa.service.ResourceService;
import com.shj.em.base.support.ResMsg;
import com.shj.em.util.MD5Utils;
import com.shj.em.util.ShiroUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;


@RestController
public class LoginController{

    @Autowired
    private ResourceService resourceService;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private UserService userService;

    @GetMapping("/login")
    String login() {
        return "login";
    }

    @PostMapping("/ajaxLogin")
    ResMsg ajaxLogin(@RequestBody Map<String, String> params) {
        String username = params.get("username");
        String password = params.get("password");
        password = MD5Utils.encrypt(username, password);
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            User user = userService.findByUserId(username);
            String sessionId = SecurityUtils.getSubject().getSession().getId().toString();
            Map<String, String> res = new HashMap<>();
            res.put("username", user.getUsername());
            res.put("token", sessionId);
            return ResMsg.ok(res);
        } catch (AuthenticationException e) {
            return ResMsg.error(ResCode.LOGIN_REQUIRED);
        }
    }

    /**
     * 未登录，shiro应重定向到登录界面，此处返回未登录状态信息由前端控制跳转页面
     * @return
     */
    @RequestMapping(value = "/unauth")
    public ResMsg unauth() {
        return ResMsg.error(ResCode.UNAUTH);
    }

    @GetMapping("/index")
    String index(Model model) {
        List<Tree<Resource>> menus = resourceService.getMenus(ShiroUtils.getUserId());
        model.addAttribute("menus", menus);
        model.addAttribute("name", ShiroUtils.getUser().getUsername());

        model.addAttribute("picUrl","/img/default_profile.jpg");
        return "index";
    }



    
    @GetMapping("/main")
    String main(){
    	return "main";
    }
    
    @GetMapping("/logout")
	String logout() {
		ShiroUtils.logout();
		return "redirect:/login";
	}
}
